<template>
  <div class="blog-detail-page">
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载文章中...</p>
    </div>
    
    <div v-else-if="error" class="error-message">
      <p>{{ error }}</p>
      <router-link to="/blog" class="back-link">返回博客列表</router-link>
    </div>
    
    <div v-else-if="article" class="blog-detail">
      <div class="article-header">
        <img v-if="article.image" :src="article.image" :alt="article.title" class="article-cover-image">
        
        <div class="article-meta">
          <div class="article-category" v-if="article.category">
            {{ article.category.name }}
          </div>
          <h1 class="article-title">{{ article.title }}</h1>
          <div class="article-info">
            <span class="article-date">
              <i class="far fa-calendar-alt"></i> {{ formatDate(article.publishDate) }}
            </span>
            <span class="article-views">
              <i class="far fa-eye"></i> {{ article.views || 0 }} 次阅读
            </span>
          </div>
          <div class="article-tags" v-if="article.tags && article.tags.length">
            <span v-for="(tag, index) in article.tags" :key="index" class="article-tag">
              {{ tag }}
            </span>
          </div>
        </div>
      </div>
      
      <div class="article-content" v-html="formattedContent"></div>
      
      <div class="article-footer">
        <router-link to="/blog" class="back-link">
          <i class="fas fa-arrow-left"></i> 返回博客列表
        </router-link>
      </div>
      
      <div class="article-comments">
        <h2>评论 ({{ comments.length }})</h2>
        
        <div class="comment-list" v-if="comments.length">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <i class="fas fa-user-circle"></i>
            </div>
            <div class="comment-body">
              <div class="comment-author">{{ comment.username }}</div>
              <div class="comment-date">{{ formatDate(comment.createdAt) }}</div>
              <div class="comment-content">{{ comment.content }}</div>
            </div>
          </div>
        </div>
        
        <div class="no-comments" v-else>
          <p>暂无评论，来发表第一条评论吧！</p>
        </div>
        
        <div class="comment-form">
          <h3>发表评论</h3>
          
          <div v-if="commentSuccess" class="comment-success">
            评论提交成功，正在等待审核，谢谢！
          </div>
          
          <div v-else>
            <div v-if="commentError" class="comment-error">
              {{ commentError }}
            </div>
            
            <form @submit.prevent="submitComment">
              <div class="form-group">
                <label for="username">昵称</label>
                <input 
                  type="text" 
                  id="username" 
                  v-model="commentForm.username" 
                  required
                  placeholder="请输入您的昵称"
                />
              </div>
              
              <div class="form-group">
                <label for="email">邮箱</label>
                <input 
                  type="email" 
                  id="email" 
                  v-model="commentForm.email" 
                  required
                  placeholder="请输入您的邮箱 (不会公开)"
                />
              </div>
              
              <div class="form-group">
                <label for="content">评论内容</label>
                <textarea 
                  id="content" 
                  v-model="commentForm.content" 
                  rows="5"
                  required
                  placeholder="请输入您的评论"
                ></textarea>
              </div>
              
              <button type="submit" class="submit-btn" :disabled="isSubmitting">
                {{ isSubmitting ? '提交中...' : '提交评论' }}
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { articleService, commentService } from '../services';

export default {
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  
  setup(props) {
    const route = useRoute();
    const router = useRouter();
    
    // 文章相关状态
    const article = ref(null);
    const loading = ref(true);
    const error = ref(null);
    
    // 评论相关状态
    const comments = ref([]);
    const commentForm = ref({
      username: '',
      email: '',
      content: ''
    });
    const isSubmitting = ref(false);
    const commentError = ref(null);
    const commentSuccess = ref(false);
    
    // 加载文章
    const loadArticle = async () => {
      try {
        loading.value = true;
        error.value = null;
        
        const response = await articleService.getArticleById(props.id);
        article.value = response.article;
        
        if (!article.value) {
          error.value = '文章不存在';
          return;
        }
        
        // 加载文章评论
        await loadComments();
      } catch (err) {
        console.error('加载文章失败:', err);
        error.value = '加载文章失败，请稍后再试';
      } finally {
        loading.value = false;
      }
    };
    
    // 加载评论
    const loadComments = async () => {
      try {
        const response = await commentService.getArticleComments(props.id);
        comments.value = response.comments || [];
      } catch (err) {
        console.error('加载评论失败:', err);
      }
    };
    
    // 提交评论
    const submitComment = async () => {
      try {
        commentError.value = null;
        isSubmitting.value = true;
        
        await commentService.createComment(props.id, commentForm.value);
        
        // 提交成功
        commentSuccess.value = true;
        
        // 清空表单
        commentForm.value = {
          username: '',
          email: '',
          content: ''
        };
      } catch (err) {
        console.error('提交评论失败:', err);
        commentError.value = err.response?.data?.message || '提交评论失败，请稍后再试';
      } finally {
        isSubmitting.value = false;
      }
    };
    
    // 格式化内容，简单处理Markdown
    const formattedContent = computed(() => {
      if (!article.value || !article.value.content) return '';
      
      // 将Markdown转换为HTML (简单处理)
      let content = article.value.content;
      
      // 段落
      content = content.replace(/\n\n/g, '</p><p>');
      content = '<p>' + content + '</p>';
      
      // 标题
      content = content.replace(/## (.*?)(?:\n|$)/g, '<h2>$1</h2>');
      content = content.replace(/### (.*?)(?:\n|$)/g, '<h3>$1</h3>');
      
      // 粗体和斜体
      content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      content = content.replace(/\*(.*?)\*/g, '<em>$1</em>');
      
      // 链接
      content = content.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>');
      
      return content;
    });
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    };
    
    // 初始化
    onMounted(() => {
      loadArticle();
    });
    
    return {
      article,
      loading,
      error,
      comments,
      commentForm,
      isSubmitting,
      commentError,
      commentSuccess,
      formattedContent,
      submitComment,
      formatDate
    };
  }
}
</script>

<style scoped>
.blog-detail-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.loading-indicator {
  text-align: center;
  padding: 50px 0;
}

.spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  text-align: center;
  padding: 50px 0;
  color: #721c24;
}

.article-header {
  margin-bottom: 30px;
}

.article-cover-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 20px;
}

.article-category {
  display: inline-block;
  padding: 5px 12px;
  background-color: #e9ecef;
  border-radius: 20px;
  font-size: 14px;
  margin-bottom: 10px;
}

.article-title {
  font-size: 2.5rem;
  margin: 10px 0;
  line-height: 1.3;
}

.article-info {
  display: flex;
  gap: 20px;
  color: #6c757d;
  margin-bottom: 15px;
}

.article-date i, .article-views i {
  margin-right: 5px;
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
}

.article-tag {
  padding: 5px 10px;
  background-color: #f8f9fa;
  border-radius: 20px;
  font-size: 14px;
}

.article-content {
  font-size: 1.1rem;
  line-height: 1.7;
  color: #343a40;
  margin-bottom: 40px;
}

.article-content :deep(h2) {
  margin-top: 40px;
  margin-bottom: 20px;
  font-size: 1.8rem;
}

.article-content :deep(h3) {
  margin-top: 30px;
  margin-bottom: 15px;
  font-size: 1.5rem;
}

.article-content :deep(p) {
  margin-bottom: 20px;
}

.article-content :deep(a) {
  color: #007bff;
  text-decoration: none;
}

.article-content :deep(a:hover) {
  text-decoration: underline;
}

.article-footer {
  margin-bottom: 40px;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  color: #007bff;
  text-decoration: none;
}

.back-link:hover {
  text-decoration: underline;
}

.article-comments {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

.article-comments h2 {
  margin-bottom: 20px;
}

.comment-list {
  margin-bottom: 30px;
}

.comment-item {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.comment-avatar {
  font-size: 2.5rem;
  color: #6c757d;
}

.comment-body {
  flex: 1;
}

.comment-author {
  font-weight: bold;
  margin-bottom: 5px;
}

.comment-date {
  font-size: 0.9rem;
  color: #6c757d;
  margin-bottom: 10px;
}

.comment-content {
  line-height: 1.5;
}

.no-comments {
  text-align: center;
  padding: 20px;
  color: #6c757d;
  margin-bottom: 30px;
}

.comment-form h3 {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.submit-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #0069d9;
}

.submit-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.comment-success {
  padding: 15px;
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  color: #155724;
  border-radius: 4px;
  margin-bottom: 20px;
}

.comment-error {
  padding: 15px;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  color: #721c24;
  border-radius: 4px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .article-title {
    font-size: 2rem;
  }
  
  .article-content {
    font-size: 1rem;
  }
}
</style> 